//
//  ComicsListViewController.m
//  SweetComics
//
//  Created by LeeZhe on 15/2/2.
//  Copyright (c) 2015年 LeeZhe. All rights reserved.
//

#import "ComicsListViewController.h"
#import "ComicsListCell.h"
#import "AFHTTPRequestOperationManager.h"
#import "MJRefresh.h"
#import "MJRefreshBaseView.h"
#import "MJRefreshConst.h"
#import "MJRefreshHeaderView.h"
#import "DetailViewController.h"
#import "MBProgressHUD.h"
@interface ComicsListViewController ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>
@property (nonatomic,retain)UITableView *tableView;
@property (nonatomic,retain)NSMutableArray *arr;
@property (nonatomic, retain)MBProgressHUD *progress;
@end

@implementation ComicsListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.temp = 2;
    self.arr = [NSMutableArray array];
    [self createView];
    [self netWork];
//    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@""]]
    
    [self head];
    
}

- (void)creatProgress
{
    self.progress = [[[MBProgressHUD alloc]initWithView:self.view]autorelease];
    [self.view addSubview:self.progress];
    self.progress.labelFont = [UIFont systemFontOfSize:10];
    self.progress.labelText = @"努力加载中";
    [self.progress show:YES];
}




- (void)createView
{
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [self.view setPreservesSuperviewLayoutMargins:NO];
    [self.view setShouldGroupAccessibilityChildren:NO];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
- (void)netWork
{
    [self creatProgress];
//  __block ComicsListViewController *comicsVC = self;
    NSString *url = [NSString stringWithFormat:@"%@%@%@",kComicsList,self.comic_list_id,kUrlTwo];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSMutableDictionary *dic = responseObject;
        NSMutableArray *comicArr = [dic objectForKey:@"data"];
//        NSLog(@"dic ~~~~%@",comicArr);
        if (!comicArr) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有漫画哦" delegate: self cancelButtonTitle:@"好吧" otherButtonTitles:nil] ;
            [alertView show];
            [alertView release];
            [self.view addSubview:alertView];
            [_progress hide:YES];
            
        }else
        {
            for (NSDictionary *dic in comicArr) {
                ComicList *comics = [[ComicList alloc] init];
                [comics setValuesForKeysWithDictionary:dic];
                [self.arr addObject:comics];
                //            NSLog(@"少年 %@",comics);
                [comics release];
            }
            [_progress hide:YES];

        }
        [self.tableView reloadData];

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)head
{
    [self.tableView addHeaderWithTarget:self action:@selector(headRefresh)];
    [self.tableView addFooterWithTarget:self action:@selector(footRefresh)];
    self.tableView.headerPullToRefreshText = @"下拉刷新";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableView.headerRefreshingText = @"正在刷新中,请稍后";
    
    self.tableView.footerPullToRefreshText = @"上拉加载更多数据";
    self.tableView.footerReleaseToRefreshText = @"松开马上加载更多数据";
    self.tableView.footerRefreshingText = @"正在加载中,加油加油";
}
// 下拉刷新
- (void)headRefresh
{
    //自动刷新
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.tableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView headerEndRefreshing];
    });
}
// 上拉加载
- (void)footRefresh
{
//    ++self.temp;
   
     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
         
         NSString *strUrl = [NSString stringWithFormat:@"%ld",((long)self.temp + 1)];
         
         
         NSString *str = [NSString stringWithFormat:@"%@%@/listcnt/12/page/%@/clientType/0",kComicsList,self.comic_list_id,strUrl];
         AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
         manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
         [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
             NSMutableDictionary *dic = responseObject;
             NSMutableArray *comicArr = [dic objectForKey:@"data"];
             for (NSMutableDictionary *dicOne in comicArr) {
                 ComicList *comic = [[ComicList alloc] init];
                 [comic setValuesForKeysWithDictionary:dicOne];
                 [self.arr addObject:comic];
             }
             [self.tableView reloadData];
             
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             NSLog(@"%@",error);
         }];
         [self.tableView footerEndRefreshing];
         
         self.temp++;
         
     });
    
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ComicList *comics = [self.arr objectAtIndex:indexPath.row];
    DetailViewController *detailVC = [[DetailViewController alloc] init];
        detailVC.comic = comics;
    [self.navigationController pushViewController:detailVC animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 140;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ComicList *comics = [self.arr objectAtIndex:indexPath.row];
        static NSString *one = @"one";
        ComicsListCell *cellOne = [tableView dequeueReusableCellWithIdentifier:one];
        if (!cellOne) {
            cellOne = [[[ComicsListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:one] autorelease];
        }
        [cellOne setComics:comics];
    
   
    return cellOne;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arr.count;
}
- (void)dealloc
{
    [_comic_list_id release];
    [_progress release];
    [_arr release];
    [_tableView release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
